package com.xywl.escort.view.pay

import android.os.Bundle
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.AddCashFlowReq
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.bean.ProductPayApplyReq
import com.xywl.escort.common.Constant
import com.xywl.escort.common.Constant.EventMessage.WITHDRAW_SUCCESS
import com.xywl.escort.common.Constant.EventType.EVENT_WITHDRAW_SUCCESS
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.MD5
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.CustomDialog
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_verify_pay_pwd.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.math.BigDecimal
import javax.inject.Inject

/**
 * 校验支付密码界面
 */
@Route(path = "/xy/verify/pay/pwd")
class VerifyPayPwdActivity : BaseActivity(), VerifyPayPwdContract.View {

    @Autowired
    @JvmField
    var title = ""

    @Autowired
    @JvmField
    var path = ""

    @Autowired
    @JvmField
    var type = 0

    @Autowired
    @JvmField
    var withdrawBean: AddCashFlowReq? = null

    @Autowired
    @JvmField
    var recordId = ""

    @Autowired
    @JvmField
    var orderId = ""

    @Autowired
    @JvmField
    var bankCardNo = ""

    @Autowired
    @JvmField
    var payment = BigDecimal("0")

    @Autowired
    @JvmField
    var deduction = BigDecimal("0")

    @Autowired
    @JvmField
    var payType = 0

    @Autowired
    @JvmField
    var payStatus = 0

    @Inject
    lateinit var mPresenter: VerifyPayPwdContract.Presenter

    private var mDialog: CustomDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_verify_pay_pwd)
        ARouter.getInstance().inject(this)
        initView()
        mPresenter.takeView(this)
        addListener()
        EventBus.getDefault().register(this)
        Timber.e("type=$type")
    }

    private fun initView() {
        showBackButton()
        if (!TextUtils.isEmpty(title)) {
            setTitleText(title)
        } else {
            setTitleText("校验支付密码")
        }
    }

    private fun addListener() {
        val userId = RxSPTool.getString(this, USER_ID)
        edit_pwd.setOnPasswordChangeListener { password ->
            if (password.length == 6) {
                val pwd = MD5.encrypt(password)
                if (type == 2) {
                    // 认购第二步-支付申请
                    mPresenter.payApply(recordId, pwd)
                } else if (type == 3) {
                    // 商品购买 第一步 支付申请
                    val req = ProductPayApplyReq()
                    req.orderId = orderId
                    req.bankCardNo = bankCardNo
                    req.payment = payment
                    req.deduction = deduction
                    req.payType = payType
                    req.type = payStatus
                    req.payPassword = pwd
                    mPresenter.productPayApply(req, pwd)
                } else {
                    // 正常校验支付密码
                    mPresenter.verifyPayPwd(userId, pwd)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("VerifyPayPwdActivity").e("event.message=" + event.message)
        Timber.tag("VerifyPayPwdActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_PAY_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.PAY_SUCCESS) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun verifyPayPwdSuccess() {
        if (type == 0) {
            // 正常的校验支付密码成功
            if (!TextUtils.isEmpty(path)) {
                ARouter.getInstance().build(path).navigation()
            } else {
                Timber.e("path=null")
            }
            finish()
        } else if (type == 1) {
            // 提现时 校验支付密码成功
            mPresenter.addCashFlow(withdrawBean)
        }
    }

    override fun verifyPayPwdFailure(msg: String) {
        ToastUtil.showTip(this, msg)
    }

    override fun payApplySuccess(data: String?, payPwd: String?) {
        // 认购第二步-支付申请 支付密码校验成功
        // 状态码=200，并且data=1时，表示不使用银行卡支付，此时支付完成，不需要再调用【支付确认】接口； 当data=2时，表示需要使用银行卡支付，支付未完成，此时需要调用【支付确认】接口
        if (data.equals("1")) {
            ToastUtil.showTip(this, "支付成功")
            EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_PAY_SUCCESS, Constant.EventMessage.PAY_BALANCE_SUCCESS))
            ARouter.getInstance()
                    .build("/xy/order/subscribe/detail")
                    .withString("id", recordId)
                    .navigation()
            finish()
        } else {
            ARouter.getInstance()
                    .build("/xy/pay/confirm")
                    .withString("id", recordId)
                    .withString("payPwd", payPwd)
                    .navigation()
        }
    }

    override fun payApplyFailure(msg: String?, payPwd: String?) {
        // 认购第二步-支付申请 支付密码校验失败
        ToastUtil.showTip(this, msg)
    }

    override fun productPayApplySuccess(data: String?, payPwd: String?) {
        // 商品付款第一步支付申请 支付密码校验成功
        if (!TextUtils.isEmpty(path)) {
            // 银行卡+余额支付
            ARouter.getInstance()
                    .build(path)
                    .withString("orderId", orderId)
                    .withString("bankCardNo", bankCardNo)
                    .withObject("payment", payment)
                    .withObject("deduction", deduction)
                    .withInt("payType", payType)
                    .withInt("payStatus", payStatus)
                    .withString("payPwd", payPwd)
                    .navigation()
        } else {
            // 余额支付
            EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_PAY_SUCCESS, Constant.EventMessage.PAY_BALANCE_SUCCESS))
            ARouter.getInstance()
                    .build("/xy/order/purchase/detail")
                    .withString("orderId", orderId)
                    .navigation()
            finish()
        }
    }

    override fun productPayApplyFailure(msg: String?, payPwd: String?) {
        // 商品付款第一步支付申请 支付密码校验失败
        ToastUtil.showTip(this, msg)
    }

    override fun addCashFlowSuccess(resp: BaseResp?) {
        mDialog = CustomDialog.Builder(this)
                .setMessage("提现操作成功！！！")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                    EventBus.getDefault().post(MessageEvent(EVENT_WITHDRAW_SUCCESS, WITHDRAW_SUCCESS))
                    mDialog!!.dismiss()
                    finish()
                }.create()
        mDialog!!.show()
    }

    override fun addCashFlowFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun onDestroy() {
        super.onDestroy()
        mDialog?.let {
            mDialog!!.dismiss()
        }
        EventBus.getDefault().unregister(this)
    }
}
